<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/20
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Cache\CacheManager as Cache;
use Imi\Config;
use ImiApp\ApiServer\Api\Model\Subj;

/**
 * 考试答题接口📝
 * @Auth(name="token",nologin={"get_subj"})
 * @Controller("/store.exam/")
 */
class Exam extends StoreBean
{
    protected $noNeedLogin = ['get_subj'];
    protected $noNeedRight = ['*'];


    /**
     * 是否要考试
     *
     * @param string $code 邀请码
     * @param string $tel 辅导员手机号
     * @return void
     * @Action
     */
    public function is_exam($code = null, $tel = null)
    {
        $msg = '需要考试';
        $data['test_status'] = 0; //考试状态:0=未知,1=免考,2=已考
        if ($code || $tel) {
            //查询用户id
            if ($code)
                $user = Db::name('user')->where('invite_code', '=', $code)->select()->get();
            if ($tel)
                $user = Db::name('user')->where('mobile', '=', $tel)->select()->get();
            if (!$user)
                return $this->error('没有该辅导员');

            $data['pid'] = $user['id'];
            if ($user['set_id'] > 3) {
                $msg = '已通过考试';
                $data['test_status'] = 1; //考试状态:0=未知,1=免考,2=已考
            }
            $exam = Db::name('exam')->where('user_id', '=', $this->auth->user()->id)->where('scores', '>=', config('store_scores_pass'))->select()->get();
            if ($exam) {
                $msg = '已通过考试';
                $data['test_status'] = 2; //考试状态:0=未知,1=免考,2=已考
                $data['scores'] = $exam['scores'];
                $data['exam_id'] = $exam['id'];
            }     
        } else {
            //查询用户是否已经通过考试   
            $exam = Db::name('exam')->where('user_id', '=', $this->auth->user()->id)->where('scores', '>=', config('store_scores_pass'))->select()->get();
            if ($exam) {
                $msg = '已通过考试';
                $data['test_status'] = 2; //考试状态:0=未知,1=免考,2=已考
                $data['scores'] = $exam['scores'];
                $data['exam_id'] = $exam['id'];
            }
        }
        return $this->success($msg, $data);
    }

    /**
     * 获取考试ID
     *
     * @return void
     * @Action
     */
    public function get_exam()
    {
        $exam = Db::name('exam')->where('user_id', '=', $this->auth->user()->id)->where('e_time', '<', 1)->select()->get();
        if ($exam) {
            return $this->success('考试id', $exam['id']);
        } else {
            $id = Db::name('exam')->insert(['user_id' => $this->auth->user()->id, 's_time' => time()])->getLastInsertId();
            return $this->success('考试id', $id);
        }
    }


    /**
     * 获取题目
     *
     * @param integer $limit 数量默认1
     * @return void
     * @Action
     */
    public function get_subj(?int $limit = 1)
    {
        var_dump(__METHOD__, $limit);
        // $this->redis = $this->getRedis();
        // $this->redis
        // $list_ids = Db::name('subj')->column('id');
        // halt($list_ids);

        // $data = Db::name('subj')->where('id','>',0)->select()->getArray();
        // $data = Db::name('subj')->select()->getArray();

        // if($this->today($this->auth->user()->id)){  //  今天回答没有

        //     $get_poster = $this->get_poster($this->auth->user()->id);//创建一张海报

        //     return $this->error('今天回答完成!',$get_poster,3);
        // }

        $data = Cache::get('redis', 'all_subj');
        if (!$data) {
            $data = Db::name('subj')
                ->where('subj_status','=','1')
                // Subj::dbQuery()
                // ->where('id','>',0)
                // fieldRaw('answer,createtime', true) //subj_status,
                ->select()
                ->getArray();

            if(!$data){
                return $this->error('未查询到题库数据',$limit);
            }
            Cache::set('redis', 'all_subj', $data, 600);
        }
        if ($limit == 1) {
            $new_data = $data[array_rand($data, $limit)];
        } else {
            if (sizeof($data) < $limit)
                $limit = sizeof($data);
            $ids = array_rand($data, $limit);
            $new_data = array();
            foreach ($ids as $key => $val) {
                $new_data[] = $data[$val];
            }
        }




        return $this->success('ok', $new_data);
    }






    /**
     * 验证答案
     */
    protected function verify_the_answer($id, $answer)
    {
        $subj = Subj::find(['id' => $id]);
        if (!$subj) {
            return $this->error('没有此题');
        }

        if ($answer == $subj['answer']) {
            return true;
        } else {
            return false;
        }
    }



    /**
     * 提交答案（多题）
     * @param int $exam_id 考试ID
     * @param string $content 题目+答案{"id":"1","answer":"A"}
     * @return void
     * @Action
     */
    public function many_submit_answers(?int $exam_id = null, $content = null)
    {
        // halt(htmlspecialchars_decode($content));
        if (!$exam_id)
            return $this->error('请获取考试id');
        $exam = Db::name('exam')->where('id', '=', $exam_id)->where('user_id', '=', $this->auth->user()->id)->select()->get();
        if (!$exam)
            return $this->error('您没有该考试');
        if ($exam['e_time'] > 0)
            return $this->error('该考试已结束' . date('Y-m-d H:i', $exam['e_time']), $exam);

        $num = 0; //正确数量
        $arr = json_decode(htmlspecialchars_decode($content), true);
        if (!$arr)
            return $this->error('请传输答案内容');
        foreach ($arr as $key => $val) {
            $id = $val['id'];
            $answer = $val['answer'];

            if ($this->verify_the_answer($id, $answer)) {
                $num++;
            }
            $data = [];
            //存储答题 
            $data['user_id'] = $this->auth->user()->id;
            $data['subj_id'] = $id;
            $data['answer'] = $answer;
            $data['time'] = time();
            $data['date'] = date('Y_m_d');
            $data['exam_id'] = $exam_id;

            Db::name('submit_subj')->insert($data)->getLastInsertId();
        }

        Db::name('exam')->where('id', '=', $exam_id)->update(['scores' => $num, 'e_time' => time()]);

        $store_scores_pass = config('store_scores_pass');
        if ($num >= $store_scores_pass) {
            //通过考试
            // Db::name('store')->where('id', $this->store_id)->update(['exam_scores' => $num, 'test_status' => '2']); //考试状态:0=未知,1=免考,2=已考
            return $this->success('考试通过', $num);
        }
        return $this->error('本次考试不合格', $num);
    }



    /**
     * 提交答案（单题）
     *
     * @param string $id 题目id
     * @param string $answer 答案内容
     * @return void
     * @Action
     */
    public function submit_answers(?int $id, $answer)
    {
        if ($this->verify_the_answer($id, $answer)) {
            //存储答题 
            $data['user_id'] = $this->auth->user()->id;
            $data['subj_id'] = $id;
            $data['answer'] = $answer;
            $data['time'] = time();
            $data['date'] = date('Y_m_d');

            Db::name('submit_subj')->insert($data)->getLastInsertId();

            $key = date('Y_m_d') . '_user' . $this->auth->user()->id;
            $data = Cache::tag('submit_subj')->set($key, $id);


            // if(strtotime(config('hot_time'))<time()){
            //     return $this->error('活动时间已过');
            // }
            $get_poster = $this->get_poster($this->auth->user()->id); //创建一张海报

            return $this->success('回答正确', $get_poster, 3);
        } else {
            return $this->error('需要再接再厉');
        }
    }



    // /**
    //  * 今天是否答题正确了
    //  *
    //  * @param [type] $user_id
    //  * @return void
    //  */
    // protected function today($user_id)
    // {
    //     $key = date('Y_m_d') . '_user' . $user_id;
    //     $data = Cache::get($key);
    //     if (!$data) {
    //         return false;
    //     } else {
    //         return true;
    //     }
    // }

    // /**
    //  * 获取海报
    //  *
    //  * @param [type] $user_id
    //  * @return void
    //  */
    // protected function get_poster($user_id)
    // {
    //     // $name = date('Y_m_d').'_user'.$user_id;
    //     $key = date('Y_m_d') . '_image';
    //     $data = Cache::get($key);
    //     if (!$data) {

    //         Cache::set($key, Db::name('image')->where('date', date('Y_m_d'))->value('image'), 120);
    //         $data = Cache::get($key);
    //     }
    //     return $data;
    // }



    // /**
    //  * 测试接口获取今天海报地址
    //  *
    //  * @param Type $var
    //  * @return void
    //  */
    // public function test_image()
    // {
    //     echo $this->get_poster(1);
    // }
}
